class Restaurants::FoodsController < Restaurants::RestaurantsController
    before_action :get_food_types
    before_action :init_breadcrumb
    before_action :get_food,only:[:edit,:update,:unpublished,:published,:destroy,:show]

    def index
        food_type_id = params[:food_type_id]
        if food_type_id.present?
            @foods = Food.where(food_type_id: food_type_id)
            @food_type = FoodType.find params[:food_type_id]
            @nav_title = @food_type.name
        else
            @nav_title = "所有菜品"
            @foods = Food.where(food_type_id: @restaurant.food_types.map(&:id))
        end    
        add_breadcrumb(create_nav '菜品管理','#')
    end    

    def show
       add_breadcrumb(create_nav '菜品管理','/restaurants/foods') 
       add_breadcrumb(create_nav @food.name,'#')
       @nav_title = @food.name

    end    

    def new
        set_new_food_breadcrumb
        @food = Food.new
    end    

    def edit
        set_edit_food_breadcrumb
    end    

    def published
        @food.is_published = true
        @food.save
        redirect_to action: :index
    end    

    def unpublished
        @food.is_published = false
        @food.save
        redirect_to action: :index
    end 

    def update
        if @food.update_attributes(food_params)
            redirect_to action: :show,id: @food.id
        else
            set_edit_food_breadcrumb
            render :edit
        end    
    end
    
    def create
        @food = Food.new(food_params)
        if @food.show_price == 0
            @food.show_price = nil
        end    
        if @food.save
            redirect_to action: :show,id: @food.id
        else
            set_new_food_breadcrumb
            render :new    
        end    
    end    

    def destroy
        @food.destroy
        redirect_to action: :index
    end    


    private
    def get_food
      @food = Food.find params[:id]  
    end 

    def set_new_food_breadcrumb
         @nav_title = "新建菜品"
        add_breadcrumb create_nav('菜品管理','/restaurants/foods')
        add_breadcrumb create_nav('新建菜品', '/restaurants/foods/new')
    end    

    def set_edit_food_breadcrumb
        @nav_title = "修改#{@food.name}"
        add_breadcrumb(create_nav '菜品管理','/restaurants/foods') 
        add_breadcrumb(create_nav @food.name,"/restaurants/foods/#{@food.id}")
        add_breadcrumb(create_nav "修改","#")
    end    

    def get_food_types
        @food_types = FoodType.where(restaurant_id:session[:restaurant_id])
    end  

    def food_params
        params.require(:food).permit(:name,:food_type_id,:attachment,:sell_price,:show_price,:description)
    end 

end
